package cn.wizzer.app.user.modules.service.impl;

import cn.wizzer.app.user.modules.models.UserAddress;
import cn.wizzer.app.user.modules.services.UserAddressService;
import cn.wizzer.framework.base.Result;
import cn.wizzer.framework.base.service.BaseServiceImpl;
import cn.wizzer.framework.base.service.CommonDBService;
import cn.wizzer.framework.page.Pagination;
import cn.wizzer.util.CommonUtil;
import com.alibaba.dubbo.config.annotation.Service;
import org.nutz.aop.interceptor.ioc.TransAop;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;

@IocBean(args = {"refer:dao"})
@Service(interfaceClass = UserAddressService.class)
public class UserAddressServiceImpl extends BaseServiceImpl<UserAddress> implements UserAddressService {
    public UserAddressServiceImpl(Dao dao) {
        super(dao);
    }

    @Inject
    private CommonDBService dbService;

    @Override
    public Pagination listPage(Integer pageNumber, int pageSize, String userId) {
        Sql sql = Sqls.create("select * from user_address " +
                "$condition ");
        Sql countSql = Sqls.create("select count(1) from user_address " +
                "$condition ");
        Cnd cnd = Cnd.where("userId", "=", userId).and("delFlag", "=", 0);
        sql.setCondition(cnd);
        sql.appendSourceSql("order by opAt desc");
        countSql.setCondition(cnd);
        return this.listPage(pageNumber, pageSize, sql, countSql);
    }

    @Override
    public Result validate(UserAddress userAddress) {
        if (Strings.isBlank(userAddress.getReceiverName())) {
            return Result.error("收货人姓名不能为空");
        }
        if (Strings.isBlank(userAddress.getReceiverPhone())) {
            return Result.error("手机号码不能为空");
        }else {
            // 校验手机号码
            CommonUtil.isPhone(userAddress.getReceiverPhone());
        }
        if (Strings.isBlank(userAddress.getAddr())) {
            return Result.error("收货地址不能为空");
        }
        return Result.success();
    }

    // 设置默认收货地址
    @Aop(TransAop.READ_COMMITTED)
    @Override
    public void setDefault(String id, String appid) {
//        UPDATE user_address SET addr_default = 0 WHERE addr_default = 1 and userId = 'xx'
//        UPDATE user_address SET addr_default = 1 WHERE id = 'yy'
        StringBuffer sb = new StringBuffer()
                .append("UPDATE user_address SET addr_default = 0 WHERE addr_default = 1 and userId = '")
                .append(appid)
                .append("'");
        this.execute(Sqls.create(sb.toString()));

        sb.setLength(0);// 清空StringBuffer
        sb.append("UPDATE user_address SET addr_default = 1 WHERE id = '").append(id).append("'");
        this.execute(Sqls.create(sb.toString()));

    }

}
